<template>
  <div class="share-space-wrap">
    <div class="banner">
      <el-upload
          class="avatar-uploader"
          ref="upload"
          :action="action"
          :show-file-list="false"
          :on-success="handleSuccess"
          :headers="uploadHeaders"
      >
        <img v-if="imageUrl" :src="imageUrl" class="space-avatar"/>
        <el-icon v-else class="avatar-uploader-icon">
          <Plus/>
        </el-icon>
      </el-upload>
      <div class="space-info-wrap">
        <div class="space-name">智联空间</div>
        <div class="description">技术和经验分享</div>
        <div class="members">
          <!-- <div class="avatar-group"><el-avatar></el-avatar><el-avatar></el-avatar></div> -->
        </div>
      </div>
    </div>
    <div class="auto-complete">
      <el-autocomplete v-model="searchItem"
                       class="main-autocomplete"
                       :fetch-suggestions="mainQuerySearch"
                       popper-class="my-autocomplete"
                       @select="handleSearch"
                       value-key="name"
                       @keyup.enter="overallQuerySearch"
                       clearable
                       @clear="searchFlag= false"
                       placeholder="搜索文档">
        <template #suffix>
          <el-icon class="el-input__icon" @click="overallQuerySearch">
            <search/>
          </el-icon>
        </template>
        <template #default="{item}">
          <div class="search-value">
            <div class="search-result-name" v-html="hightlightValue(item.name,searchItem)"></div>
            <div class="search-result-path">
              <el-tag class="search-result-tag1" effect="dark">{{ typeSelect[item.type - 1].label }}</el-tag>
              <el-tag class="search-result-tag2" round effect="dark">{{ item.ancestorsName || '根目录' }}</el-tag>
            </div>
            <el-divider class="search-divider"></el-divider>
          </div>
        </template>
      </el-autocomplete>
    </div>
    <div class="content" id="shareSpaceId">
      <el-button type="primary" class="new-folder-button" v-show="activeTab==='menu'" @click="getFirstIndexSpaceDirectoryTreeData">
        <span class="plus">+</span>&nbsp;新建文件夹
      </el-button>
      <el-tabs v-model="activeTab" class="space-tab" @tab-click="handleSelect">
        <el-tab-pane name="menu" label="目录" class="right-text">
          <keep-alive>
            <Catalogue :activeName="activeNames" v-model:catalogueType="catagolueType"
                       v-if="activeTab === 'menu' && !searchFlag"/>
          </keep-alive>
          <SearchList :links="links"
                      @closeCard="closeSearchCard"
                      :key-word="searchItem"
                      :isEmptyResult="isEmptyResult"
                      :type-select="typeSelect"
                      v-if="activeTab === 'menu'&& searchFlag"></SearchList>
        </el-tab-pane>
        <el-tab-pane name="dynamic" label="动态" class="right-text">
          <Dynamic v-if="activeTab === 'dynamic'" @on-change="getDynamicData" @onJumpToCatalogue="jumpToCatalogue"/>
        </el-tab-pane>
        <el-tab-pane name="statics" label="统计" class="right-text">
          <Statics v-if="activeTab === 'statics'"/>
        </el-tab-pane>
        <el-tab-pane name="mine" label="我的" class="right-text">
          <keep-alive>
            <Mine v-if="activeTab === 'mine'"/>
          </keep-alive>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog
        v-model="centerDialogVisible"
        title="新建文件夹"
        width="30%"
        @close="closeDialog"
        align-center
    >
      <el-form :model="form" :rules="rules" label-width="120px" ref="ruleFormRef" class="demo-ruleForm">
        <el-form-item label="文件夹类别:" prop="type">
          <el-select v-model="form.type" class="m-2" placeholder="请选择" @change="changeSelectOption"
                     style="width:75%" :disabled="typeShow">
            <el-option
                v-for="item in typeSelect"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上级文件夹:" prop="parentId">
          <el-tree-select
              :props="defaultProps"
              v-model="form.parentId"
              :data="treeData"
              check-strictly
              :render-after-expand="false"
              placeholder="请选择"
              style="width:75%"
              @change="changeParentNode"
              clearable
              @clear="clearParentDir"
          />
        </el-form-item>
        <el-form-item label="文件夹名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入" style="width:75%"/>
        </el-form-item>

        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="1" :max="maxSort" style="width:75%"/>
        </el-form-item>

      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel"
        >取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)" color="#00A298">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {nextTick, onMounted, provide, reactive, ref, toRefs} from 'vue'
import Catalogue from '@/components/homeShareSpace/Catalogue.vue'
import Dynamic from '@/components/homeShareSpace/Dynamic.vue'
import Statics from '@/components/homeShareSpace/Statics.vue'
import Mine from '@/components/homeShareSpace/Mine.vue'
import FrontApi from '@/api/front'
import {ElMessage} from 'element-plus'
import router from "@/router";
import eventBus from '@/utils/event_bus'
import {getToken, setToken} from "@/utils/auth";
import useDocumentStore from "@/store/modules/document";
import SearchList from "@/components/homeShareSpace/SearchListCard.vue";

export default {
  components: {
    Catalogue,
    Dynamic,
    Statics,
    Mine,
    SearchList
  },
  setup() {
    const typeShow = ref(false);
    const store = useDocumentStore()
    const ruleFormRef = ref();
    const value = ref()
    const centerDialogVisible = ref(false)
    const upload = ref()
    const activeTab = ref()
    const squareUrl = '@/assets/img/share_space/heart.png' // 空间图片,先写死，以后在后台配置
    const showFlag = ref('true');
    let imageUrl = ref('')
    const action = ref('/api/admin/front/updateSpaceAvatar');
    const searchItem = ref('');
    const links = ref([])
    const catagolueType = ref()
    const searchMod = ref("2")
    const searchFlag = ref(false)
    const isEmptyResult = ref(true)
    const maxSort = ref(1)

    let hash = location.href;
    if (hash.indexOf('?token=') !== -1) {
      setToken(hash.split('?token=')[1])
    }

    // const directoryType=ref([])
    const defaultProps = {  //规定
      children: "children",
      label: "name",
      value: "id"
    };

    const typeSelect = ref([]);
    var data = reactive({
      personCount: 0,
      treeData: [],
      activeNames: []
    })
    var form = reactive({
      parentId: value,
      name: '',
      type: '',
      orderNum: 1
    })

    const getDynamicData = (item) => {
      handleSearch(item);
      sessionStorage.setItem('activeMenu', 'menu')
    }
    const validateParentId = (rule, value, callback) => {
      if (value === '' || value === undefined) {
        callback(new Error("请选择上级文件夹"))
      }
      callback()
    }
    const validateName = (rule, value, callback) => {
      if (value === '' || value === undefined) {
        callback(new Error('请输入文件夹名称'))
      }
      callback()
    }
    const validateType = (rule, value, callback) => {
      if (value === '' || value === undefined) {
        callback(new Error("请输入文件夹类别"))
      }
      callback()
    }

    //表单校验
    const rules = reactive({
      // parentId: [{validator: validateParentId, trigger: 'blur'}],
      name: [{validator: validateName, trigger: 'blur', required: true}],
      type: [{validator: validateType, trigger: 'change', required: true}],
    })

    const mainQuerySearch = (searchItem, cb) => {
      if (searchMod.value === "1") {
        if (searchItem && searchItem.trim() !== '') {
          FrontApi.spaceSearch(searchItem).then(res => {
            searchFlag.value = false
            links.value = res.data
            cb(links.value)
          })
        } else {
          cb([])
        }
      } else {
        cb([])
      }
    }

    const overallQuerySearch = () => {
      if (searchMod.value === "2") {
        if (searchItem.value && searchItem.value.trim() !== '') {
          FrontApi.spaceSearch(searchItem.value).then(res => {
            isEmptyResult.value = res.data.length === 0;
            activeTab.value = 'menu'
            links.value = res.data
            searchFlag.value = true
          })
        }
      }
    }

    const hightlightValue = (val, keyword) => {
      const Reg = new RegExp(keyword, 'i');
      if (val) {
        return val.replace(Reg, `<span style="color: #409EFF;font-weight: bold ">${keyword}</span>`);
      }
    }

    const closeSearchCard = () => {
      searchFlag.value = false
    }

    const updateCatalogue = (val) => {
      catagolueType.value = val
    }

    const uploadHeaders = reactive({
      Authorization: 'Bearer ' + getToken()
    })


    const handleSearch = (item) => {
      activeTab.value = 'menu'
      if (item.documentId !== undefined) {
        data.activeNames = []
        getParentNode(item.documentId, null)
      } else {
        FrontApi.getDirectoryFirstDoc(item.id).then(res => {
          if (res.data !== undefined) {
            data.activeNames = []
            getParentNode(res.data, null)
          } else {
            getParentNode(null, item.id)
          }
        })
      }
    }

    const closeDialog = () => {
      ruleFormRef.value.resetFields()
    }

    const jumpToCatalogue = async (type) => {
      activeTab.value = 'menu'
      await nextTick()
      catagolueType.value = String(type)
    }

    const getParentNode = (docId, directoryId) => {
      data.activeNames = [];
      FrontApi.getParentNode(docId, directoryId).then(res => {
        catagolueType.value = String(res.data[0].type)
        res.data.forEach(e => {
          data.activeNames.push(e.name)
        })
      })
    }
    const changeParentNode = (val) => {
      if (val) {
        FrontApi.getEchoDirectory(val).then(res => {
          let index = res.data.type;
          form.type = typeSelect.value.find(item => parseInt(item.value) === index)
        })
      }
      form.orderNum = 1;
      FrontApi.getMaxOrder(null, val).then((res) => {
        maxSort.value = res.data === undefined ? 1 : res.data + 1
      })
    }


    const clearParentDir = () => {
      form.orderNum = 1;
      if (form.type !== null && form.type !== undefined) {
        FrontApi.getMaxOrder(form.type, 0).then((res) => {
          maxSort.value = res.data === undefined ? 1 : res.data + 1
        })
      }
    }

    const cancel = () => {
      centerDialogVisible.value = false;
      ruleFormRef.value.resetFields()
      typeShow.value = false;
    }
    const submitForm = (ruleForm) => {
      ruleForm.validate((valid) => {
        if (valid) {
          FrontApi.addSpaceDirectory(form).then(res => {
            if (res.code === 200) {
              eventBus.emit("updateCatalogueBus", String(form.type))
              ElMessage({
                message: '添加成功',
                type: 'success',
              })
              centerDialogVisible.value = false;
              form.parentId = null;
              form.name = '';
              form.type = null;
              typeShow.value = false;
            } else {
              ElMessage({
                message: '添加失败',
                type: 'error',
              })
            }
          })
        } else {
          return false;
        }
      });
    }

    //文件类别select选择框改变选中事件
    const changeSelectOption = (val) => {
      form.orderNum = 1;
      FrontApi.getMaxOrder(val, 0).then((res) => {
        maxSort.value = res.data === undefined ? 1 : res.data + 1
      })
      FrontApi.getFirstIndexSpaceDirectoryTree(val).then(res => {
        data.treeData = res.data;
        value.value = undefined
      });
    }

    const getFirstIndexSpaceDirectoryTreeData = () => {
      FrontApi.getFirstIndexSpaceDirectoryTree(null).then(res => {
        data.treeData = res.data;
      });
      centerDialogVisible.value = true;
    }
    FrontApi.getPersonCount().then(res => {
      data.personCount = res.data;
    })
    FrontApi.getDirectoryType().then(res => {
      res.data.forEach(e => {
        var t = {
          value: e.dictValue,
          label: e.dictLabel
        }
        typeSelect.value.push(t)
      })
    })
    provide('typeSelect', typeSelect)
    const getSpaceData = () => {
      FrontApi.getSpaceAvatar().then(res => {
        imageUrl.value = res.data.avatar;
      })
    }

    const enterPreview = (docId, type) => {
      store.spaceDocId = docId
      router.push({path: "/DetailPreview/" + type})
    }

    const handleSuccess = () => {
      upload.value.clearFiles();//上传成功之后清除历史记录
      getSpaceData();
    }
    const handleSelect = (tab) => {
      sessionStorage.setItem('activeMenu', tab.props.name);
      switch (tab) {
        case 'menu':
          break
        case 'dynamic':
          showFlag.value = true;
          break
        case 'statics':
          showFlag.value = false;
          break
        case 'mine':
          showFlag.value = false;
          break
        default:
          showFlag.value = true;
          break
      }
    }
    const defaultActiveMenu = () => {
      var sessionStorageActiveMenu = sessionStorage.getItem('activeMenu');
      if (sessionStorageActiveMenu === null) {
        activeTab.value = 'menu';
      } else {
        activeTab.value = sessionStorageActiveMenu;
      }
    }
    onMounted(() => {
      getSpaceData();
      defaultActiveMenu();
    })
    return {
      handleSelect,
      ruleFormRef,
      upload,
      activeTab,
      squareUrl,
      showFlag,
      ...toRefs(data),
      imageUrl,
      action,
      handleSuccess,
      searchItem,
      mainQuerySearch,
      catagolueType,
      centerDialogVisible,
      closeSearchCard,
      defaultProps,
      value, searchFlag,
      hightlightValue,
      getParentNode,
      uploadHeaders,
      submitForm,
      getFirstIndexSpaceDirectoryTreeData,
      enterPreview,
      overallQuerySearch,
      handleSearch,
      form,
      typeSelect,
      cancel,
      links,
      closeDialog,
      updateCatalogue,
      changeParentNode,
      changeSelectOption,
      typeShow,
      rules,
      searchMod,
      validateParentId,
      validateName,
      validateType,
      jumpToCatalogue,
      getDynamicData,
      isEmptyResult,
      maxSort,
      clearParentDir
    }
  },
  methods: {}
}
</script>
<style scoped>
.personCount {
  font-size: 1.5rem;
  font-weight: 500;
  color: #606266;
}

.share-space-wrap {
  height: calc(100vh - 60px);
}

.banner {
  display: flex;
  align-items: center;
  padding: 0 2.4rem 0 2.4rem;
  background: rgba(91, 192, 222, 0.10);
  height: 20rem;
}

.space-avatar {
  width: 12.4rem;
  height: 12.4rem;
  background: #ffffff;
  border-radius: 8px;
}

.content {
  margin: 1.2rem 0 0 0;
  height: calc(100% - 21.2rem - 60px);
  position: relative;
}

.space-tab {
  margin: 0 2.0rem;
  min-height: 100%;
}

>>> .el-tabs__content {
  min-height: 100%;
  height: 100%;
  overflow-y: scroll;

}

.right-text {
  min-height: 100%;
}

#pane-mine.right-text {
  height: 100%;
}

/*tab下的分割线*/
:deep(.el-tabs__nav-wrap::after) {
  height: 0;
}


:deep(.el-tabs__header) {
  margin: 0;
  border-bottom: 1px solid var(--el-border-color);
}

:deep(.el-tabs__item.is-active) {
  color: #1A9B92;
}

:deep(.el-tabs__item) {
  -webkit-box-shadow: none !important;
  box-shadow: none !important;
  font-size: 15px;
}

:deep(.el-tabs__item:hover) {
  color: #1A9B92;
}

:deep(.el-tabs__active-bar) {
  width: 30px;
  background-color: #1A9B92;
}

.new-folder-button {
  position: absolute;
  width: 12.4rem;
  min-width: 86px;
  height: 3.6rem;
  background: #00A298;
  color: #ffffff;
  font-size: 1.4rem;
  right: 4rem;
  z-index: 1;
}

.plus {
  font-size: 2rem;
}

.space-info-wrap {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 12.4rem;
  margin-left: 3.6rem;
}

.space-name {
  font-size: 3.2rem;
  font-weight: 500;
}

.description {
  font-weight: 500;
  color: var(--el-text-color-regular);
  font-size: 2rem;
}

.members {
  display: flex;
  align-items: center;
}

.avatar-group {
  margin-right: 0.8rem;
}

.avatar-group :not(:first-child) {
  margin-left: -0.6rem;
}

.avatar-group .el-avatar {
  width: 3rem;
  height: 3rem;
}

.el-select {
  --el-select-input-focus-border-color: #00A298;
}

.el-input {
  --el-input-focus-border: #00A298;
  --el-input-focus-border-color: #00A298;
}

.my-autocomplete li {
  line-height: normal;
  padding: 7px;
}

.my-autocomplete li .name {
  text-overflow: ellipsis;
  overflow: hidden;
}

.my-autocomplete li .addr {
  font-size: 12px;
  color: #b4b4b4;
}

.my-autocomplete li .highlighted .addr {
  color: #ddd;
}

.main-autocomplete {
  font-size: 14px;
  width: 45rem;
}

.auto-complete {
  font-size: 14px;
  z-index: 2;
  position: absolute;
  top: 15rem;
  right: 2%;
}

.auto-complete :deep(.el-autocomplete) {
  width: 33rem !important;
}


:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-input-focus-border-color) inset;
}

:deep(>>> .el-input__inner::placeholder) {
  font-size: 13px;
}

.space-tab.el-tabs--top {
  height: 100%;
}

#pane-dynamic {
  margin-bottom: 1.6rem;
}

.searchMod-select {
  font-size: 1.5rem;
  width: 9rem;
}

.search-value {
  line-height: 3.4rem !important;
}

.search-result-name {
  font-size: 1.6rem;
}

.search-result-path {
  display: inline-flex;
  align-items: center;
}

.search-divider {
  margin: 0.4rem 0 !important;
}

.search-result-tag1 {
  background: #aa6ae5;
  border: 0;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.search-result-tag2 {
  border: 0;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.el-input__icon {
  cursor: pointer;
}

.el-input__icon:hover {
  color: #00A298;
}
</style>
